package com.github.service.captcha;


import com.github.bean.CaptchaData;
import com.github.bean.Coordinate;
import com.github.util.RandomUtil;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 抽象类，一些公共方法
 */
public abstract class Captcha<T, V, B> {


    /**
     * 创建验证码图片资源
     * @param captchaConfig 验证码配置
     * @return              验证码图片及元信息
     */
    public abstract CaptchaData<V, B> create(T captchaConfig);

    /**
     * 校验验证码
     * @param backend   后端事先保存的凭证
     * @param client    前端传入的参数
     * @return          是否校验成功
     */
    public abstract boolean check(B backend, B client);


    /**
     * 在 X,Y 区域内随机生成 1 个坐标
     *
     * @param startX X 起始范围
     * @param endX   X 结束范围
     * @param startY Y 起始范围
     * @param endY   Y 结束范围
     * @return 1 个坐标
     */
    protected Coordinate genCoordinate(int startX, int endX, int startY, int endY) {
        int x = RandomUtil.genNum(startX, endX);
        int y = RandomUtil.genNum(startY, endY);
        return new Coordinate(x, y);
    }



    /**
     * 将两张图片按照从上到下合成一张
     *
     * @param background 图 1
     * @param fragment   图 2
     * @return 合成的图片
     */
    protected BufferedImage mergeImagesVertical(BufferedImage background, BufferedImage fragment) {
        BufferedImage merge = new BufferedImage(background.getWidth(), background.getHeight() + fragment.getHeight(), background.getType());
        Graphics2D graphics = merge.createGraphics();
        graphics.drawImage(background, 0, 0, null);
        graphics.drawImage(fragment, 0, background.getHeight(), null);
        graphics.dispose();
        return merge;
    }

    /**
     * 将两张图片按照从左到右合成一张
     *
     * @param background 图 1
     * @param fragment   图 2
     * @return 合成的图片
     */
    protected BufferedImage mergeImagesHorizontal(BufferedImage background, BufferedImage fragment) {
        BufferedImage merge = new BufferedImage(background.getWidth() + fragment.getWidth(), background.getHeight(), background.getType());
        Graphics2D graphics = merge.createGraphics();
        graphics.drawImage(background, 0, 0, null);
        graphics.drawImage(fragment, background.getWidth(), 0, null);
        graphics.dispose();
        return merge;
    }

    /**
     * 对原图进行复制，达到对原图的重用
     * @param source    原图
     * @return          复制后的原图
     */
    protected BufferedImage copyImage(BufferedImage source){
        BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
        Graphics g = b.getGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
        return b;
    }






}
